#include "CRawImage.h"

//static unsigned char header[] =  {66,77,54,16,14,0,0,0,0,0,54,0,0,0,40,0,0,0,128,2,0,0,224,1,0,0,1,0,24,0,0,0,0,0,0,16,14,0,18,11,0,0,18,11,0,0,0,0,0,0,0,0,0,0};

CRawImage::CRawImage()
{
	width = 640;
	height = 480;
	bpp= 24;
	size = width*height*bpp/8;              // size in char (8 bits)
	data = (unsigned char*)calloc(size,sizeof(unsigned char));
        fileHeader = (unsigned char*)calloc(54,sizeof(unsigned char));
}

CRawImage::~CRawImage()
{
}

void CRawImage::swap()
{
  unsigned char* newData = (unsigned char*)calloc(size,sizeof(unsigned char));
  int span = width*bpp/8;
  // obraceni vzhuru nohama
  for (int j = 0;j<height;j++){
	  memcpy(&newData[span*j],&data[span*(height-1-j)],span);
	  for (int i = 0;i<width;i++){
		  char a = newData[(width*j+i)*3]; 
		  newData[(width*j+i)*3] = newData[(width*j+i)*3+2];
		  newData[(width*j+i)*3+2] = a; 
	  }
  }
  memcpy(data,newData,size);
  free(newData);
}
void CRawImage::saveBmp(const char* inName)
{
	FILE* file = fopen(inName,"wb");
	fwrite(fileHeader,54,1,file);
	fwrite(data,size,1,file);
	fclose(file);
}

bool CRawImage::loadBmp(const char* inName)
{
        FILE* file = fopen(inName,"rb");
        int w,h;
        w=h=0;
	if (file!=NULL)
	{
		fread(fileHeader,54,1,file);
                // Is file BMP file?
                if(!((fileHeader[0]==66) & (fileHeader[1]==77)))
                {
                    fprintf(stderr,"Not valid BMP file!\n");
                    return false;
                }
                w = fileHeader[18] | (fileHeader[19]<<8) | (fileHeader[20]<<16) | (fileHeader[21]<<24);
                h = fileHeader[22] | (fileHeader[23]<<8) | (fileHeader[24]<<27) | (fileHeader[25]<<24);
                if(w!=640 || h!=480)
                {
                    fprintf(stderr,"Size of image is not 640x480 pixels.\n");
                }
                else
                {
                    width = w;
                    height = h;
                }
                bpp = fileHeader[28] | (fileHeader[29]<<8);
		size = height*width*bpp/8;      // size in char (8 bits)
                delete data;
                data = (unsigned char*)calloc(size,sizeof(unsigned char));
//              printf("width: %d,height: %d,bpp: %d \n",width,height,bpp);
		fread(data,size,1,file);
		fclose(file);
		swap();
		return true;
	}
	return false;
}
